/**
 * 
 */
package com.ihome.framework.core.event.handler;

import javax.annotation.Resource;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import com.ihome.framework.core.event.PayoutDataEvent;
import com.ihome.framework.core.event.SpringTestCase;
import com.ihome.framework.core.event.IHomeEventBusHandler.EventBusWorkHandler;
import com.ihome.framework.core.event.command.AccountWaterInsertCommand;
import com.ihome.framework.core.event.command.FrozenAccountCommand;
import com.ihome.framework.core.event.command.FundOrderInsertCommand;
import com.ihome.framework.core.event.command.lua.FrozenAccountLuaCommandScript;

/**
 * @author zww
 *
 */
@Component
@Scope("prototype")
public class PayoutDataInDbHandler extends EventBusWorkHandler<PayoutDataEvent>{

    @Resource
    private FrozenAccountLuaCommandScript frozenAccountLuaCommandScript;

    /* (non-Javadoc)
     * @see com.ihome.framework.core.event.IHomeEventBus#onEvent(com.ihome.framework.core.event.IHomeEventBus.EventDto)
     */
    @Override
    public void handler(PayoutDataEvent e,long sequence,boolean endOfBatch) throws Exception {

        long threadId = Thread.currentThread().getId(); // 获取当前线程id
        String accountNo = e.getAccountNo();
        Integer money = e.getMoney();

        Assert.isTrue(((Long)frozenAccountLuaCommandScript.execute(new String[]{
                redisClient.getNamespace()+"Account-"+accountNo}, e.getMoney().toString())).intValue() == 1,"余额不足...");

        e.addCommand(new FundOrderInsertCommand(e.getRequestId(),(long)e.getMoney(), accountNo));
        e.addCommand(new FrozenAccountCommand(e.getRequestId(), (long)e.getMoney(), accountNo));
        e.addCommand(new AccountWaterInsertCommand(e.getRequestId(), (long)e.getMoney(), accountNo));
        LOGGER.info(String.format("UUID %s | Thread Id %s 数据落表并冻结金额[account:%s|status:PRE_SEND] ....",e.getRequestId(),threadId,""));
    }
}
